#!/usr/bin/python2.5
#
# (c) 2009 - Chip Turner
#
# Apache License, blah blah, it's a few hundred lines of python.

"""
There are two primary modes for %prog:

%prog -r REALM -g GUILD [ -r REP ]

"""

import collections
import logging
import os
import time
import sys
import optparse
import textwrap

import armory_lib

def main(args):
  parser = optparse.OptionParser(__doc__)
  parser.add_option("-r", "--realm", help="realm player or guild is on")
  parser.add_option("", "--eu", help="Use EU Armory instead of US armory",
                    action="store_true")
  parser.add_option("-v", "--verbose", help="show debugging output", action="store_true")

  guild_group = optparse.OptionGroup(parser, "Guild Options")
  guild_group.add_option("-g", "--guild", help="guild name to extract data for")
  guild_group.add_option("-m", "--maxrank", help="maximum rank to show results for (numeric, gm=0)",
                         type=int)
  guild_group.add_option("-l", "--level", help="minimum level to show results for", type=int, default=80)
  guild_group.add_option("-x", "--exclude", help="exclude this user", action="append")
  guild_group.add_option("", "--exclude-file", help="path to file containing names to exclude, one per line")
  parser.add_option_group(guild_group)

  options, args = parser.parse_args(args)

  if options.verbose:
    armory_lib.InitLogging(logging.DEBUG)
  else:
    armory_lib.InitLogging()

  if options.eu:
    armory_interface = armory_lib.ArmoryInterface("eu")
  else:
    armory_interface = armory_lib.ArmoryInterface("us")

  print "Report generated: %s" % time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(time.time()))
  print

  exclude = options.exclude or []
  if options.exclude_file:
    exclude.extend(l.strip() for l in open(options.exclude_file, "r").readlines())

  categories, achievement_id = None, None
  cat_id = None
  still_needed = collections.defaultdict(set)   # achievement_name -> [ player player ... ]
  members = armory_interface.ParseRoster(options.realm, options.guild)
  matching_members = 0

  rep_max = collections.defaultdict(list)  # rep -> [(player, rep), (player, rep), ...]
  for name, level, race_id, class_id, rank in members:
    if level < options.level: continue
    if options.maxrank and rank > options.maxrank: continue
    if name in exclude: continue
    matching_members += 1

    reputations = armory_interface.ParseReputation(options.realm, name)
    reputations.sort(key=lambda o: o.name)

    print "By player:"
    print "%s (Level %s Rank %d):" % (name, level, rank)
    for rep in reputations:
      print "  %s: %s (%d/%d)" % (rep.name, rep.pretty_reputation, rep.relative_value, rep.next_level)
      rep_max[rep.name].append((name, rank, rep))
    print

  print
  print "Max rep per faction:"
  for rep_name in sorted(rep_max.keys()):
    sorted_player_reps = sorted(rep_max[rep_name], key=lambda e: (e[2].position, -e[1]), reverse=True)
    player, rank, rep = sorted_player_reps[0]
    print "  %s: %s, %s - %d/%d; %d others with rep" % (rep_name, player, rep.pretty_reputation,
                                                        rep.relative_value, rep.next_level, len(sorted_player_reps) - 1)
    

if __name__ == '__main__':
  main(sys.argv[1:])
